package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    private SysMenuDao sysMenuDao;
    /**获取并封装授权信息(做授权业务时写此方法)*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==doGetAuthorizationInfo==");
        //1.获取登录用户
        SysUser user=(SysUser) principalCollection.getPrimaryPrincipal();//获取用户身份(由登录时的封装决定)
        //2.基于登录用户ID获取用户的角色ID （查询用户角色关系表）
        List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(user.getId());
        if(roleIds==null||roleIds.size()==0)
            throw new AuthorizationException();
        //3.基于角色ID获取菜单ID(查询角色菜单关系表)
        List<Integer> menuIds=sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
        if(menuIds==null||menuIds.size()==0)
            throw new AuthorizationException();
        //4.基于菜单id获取授权标识Permission (查询菜单表)
        List<String> userPermissions=sysMenuDao.findPermissions(menuIds);
        if(userPermissions==null||userPermissions.size()==0)
            throw new AuthorizationException();
        //5.封装用户授权标识信息并返回
        Set<String> setPermissions=new HashSet<>();
        for (String per:userPermissions){
            if(!StringUtils.isEmpty(per)){
                setPermissions.add(per);
            }
        }
        System.out.println("setPermissions="+setPermissions);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(setPermissions);
        return info;
    }
    /**获取并封装认证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //1.获取登录时输入的用户名
        UsernamePasswordToken uToken=(UsernamePasswordToken)authenticationToken;
        String username=uToken.getUsername();
       //2.基于用户名查询数据库中的用户信息
       SysUser user=sysUserDao.findUserByUserName(username);
       //3.校验用户是否存在
        if(user==null)throw new UnknownAccountException();
       //4.校验用户是否已被禁用
        if(user.getValid()==0)throw new LockedAccountException();
       //5.封装用户信息由底层进行密码校验
        ByteSource credentialsSalt=ByteSource.Util.bytes(user.getSalt());
        return new SimpleAuthenticationInfo(user,//principal 身份
                user.getPassword(),//hashedCredentials 已加密的密码
                credentialsSalt,//credentialsSalt 凭证盐
                getName()) ;
    }

    /**此方法中返回凭证加密对象,基于此对象对用户输入的密码进行加密操作*/
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }//对于此get方法而言，也可以重写set方法

//    @Override
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        HashedCredentialsMatcher cMatcher=new HashedCredentialsMatcher();
//        cMatcher.setHashAlgorithmName("MD5");
//        cMatcher.setHashIterations(1);
//        super.setCredentialsMatcher(cMatcher);
//    }

}
